package com.shujia.spark.mllib

import org.apache.spark.ml.classification.{LogisticRegression, LogisticRegressionModel}
import org.apache.spark.sql.{DataFrame, Dataset, Row, SparkSession}

object Demo7ImageModelTrain {
  def main(args: Array[String]): Unit = {

    val spark: SparkSession = SparkSession
      .builder()
      .appName("source")
      .master("local[8]")
      .config("spark.sql.shuffle.partitions", "8")
      .getOrCreate()

    //导入隐式转换
    import spark.implicits._
    //导入spark 所有的函数
    import org.apache.spark.sql.functions._


    //读取处理好的数据

    val data: DataFrame = spark.read.format("libsvm").load("data/imageData")


    //将数据切分成训练集和测试集
    val splitData: Array[Dataset[Row]] = data.randomSplit(Array(0.8, 0.2))

    //训练集
    val trainData: Dataset[Row] = splitData(0)
    //测试集
    val testData: Dataset[Row] = splitData(1)


    //构建算法指定参数
    val logisticRegression: LogisticRegression = new LogisticRegression()
      .setMaxIter(20)
      .setFitIntercept(true)


    //将训练集带入算法训练模型
    val model: LogisticRegressionModel = logisticRegression.fit(trainData)


    //将测试集带入模型计算准确率

    val result: DataFrame = model.transform(testData)


    //计算准确率
    result
      .select(sum(when($"label" === $"prediction", 1).otherwise(0)) / count($"label"))
      .show()


    model.save("data/imageModel")

  }

}
